package com.wei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wei.enums.EnabledEnum;
import com.wei.model.ProdPartitionDO;
import com.wei.model.ProductDO;
import com.wei.model.ProductPartitionRelDO;
import com.wei.model.ReviewDO;
import com.wei.result.R;
import com.wei.service.IPartitionService;
import com.wei.service.IProductPartitionRelService;
import com.wei.service.IProductService;
import com.wei.service.IReviewService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品分区表 前端控制器
 * </p>
 *
 * @author 蔡徐坤
 * @since 2025-07-28
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "产品分区")
@RequestMapping("/api/partition")
public class PartitionController {

    private final IPartitionService partitionService;

    private final IProductPartitionRelService productPartitionRelService;

    private final IProductService productService;

    private final IReviewService reviewService;

    @ApiOperation("分区列表")
    @GetMapping("/list")
    public R<List<ProdPartitionDO>> getPartitions() {
        List<ProdPartitionDO> res = partitionService.list(new LambdaQueryWrapper<ProdPartitionDO>()
                .eq(ProdPartitionDO::getEnabled, EnabledEnum.ENABLED.getCode()));
        return R.ok(res);
    }

    @ApiOperation("根据分区ID查询商品列表")
    @GetMapping("/list_products_by_partition_id/{partitionId}")
    public R<List<ProductDO>> getPartitionsByPartitionId(@PathVariable("partitionId") Long partitionId) {
        // 查关联
        List<ProductPartitionRelDO> rels = productPartitionRelService.list(new LambdaQueryWrapper<ProductPartitionRelDO>()
                .eq(ProductPartitionRelDO::getPartitionId, partitionId));
        System.err.println("rels:" + rels);
        // 转成ID集合
        List<Long> productIdList = rels.stream().map(ProductPartitionRelDO::getProductId).collect(Collectors.toList());
        System.err.println("productIdList:" + productIdList);
        // 查产品
        List<ProductDO> res = productService.listByIds(productIdList);
        // 查评分
        res.forEach(product -> {
            List<ReviewDO> reviews = reviewService.list(new LambdaQueryWrapper<ReviewDO>().eq(ReviewDO::getProductId, product.getId()));
            if (reviews == null || reviews.isEmpty()) {
                product.setRating(5d);
                return;
            }
            Double sum = 0d;
            for (ReviewDO review : reviews) {
                sum += review.getRating();
            }
            product.setRating(sum / reviews.size());
        });
        return R.ok(res);
    }

}
